package com.yuews.codegenerator;

import com.yuews.codegenerator.config.ConfigManager;
import com.yuews.codegenerator.generator.CodeGenerator;
import com.yuews.codegenerator.model.TableInfo;
import com.yuews.codegenerator.parser.DatabaseParser;
import com.yuews.codegenerator.template.TemplateEngine;

import java.util.List;

/**
 * 轻量级Java代码生成器主入口类
 */
public class Main {

    public static void main(String[] args) {
        System.out.println("========================================");
        System.out.println("       轻量级Java代码生成器启动         ");
        System.out.println("       版本: 1.0.0                      ");
        System.out.println("========================================");

        try {
            // 1. 检查命令行参数
            String configFilePath = args.length > 0 ? args[0] : "generator.properties";
            
            System.out.println("正在加载配置文件: " + configFilePath);

            // 2. 加载配置
            ConfigManager configManager = ConfigManager.getInstance();
            configManager.loadConfig(configFilePath);
            
            String parserType = configManager.getParserType();
            String sqlContent = null;
            
            System.out.println("使用数据库连接模式生成代码");

            // 4. 初始化模板引擎
            TemplateEngine templateEngine = new TemplateEngine(configManager.getTemplateDir());

            // 5. 创建数据库解析器，获取表信息
            DatabaseParser parser = new DatabaseParser();
            
            // 获取数据库连接信息
            String dbConnInfo = configManager.getDatabaseConnectionInfo();
            if (dbConnInfo.isEmpty()) {
                throw new IllegalArgumentException("必须配置database.connection.info");
            }
            System.out.println("正在连接数据库...");
            List<TableInfo> tables = parser.parse(dbConnInfo);
            
            // 应用表名到实体类名的映射配置
            applyTableEntityMapping(tables, configManager);

            if (tables.isEmpty()) {
                System.out.println("警告: 未从数据库中获取到任何表结构");
                return;
            }

            System.out.println("\n成功解析到 " + tables.size() + " 个表结构:");
            for (TableInfo table : tables) {
                System.out.println("- " + table.getTableName() + " (" + table.getTableComment() + ")");
            }

            // 6. 创建代码生成器并生成代码
            CodeGenerator codeGenerator = new CodeGenerator(configManager, templateEngine);
            
            int successCount = 0;
            int failCount = 0;
            
            System.out.println("\n========================================");
            System.out.println("           开始生成代码...              ");
            System.out.println("========================================");
            
            for (TableInfo table : tables) {
                try {
                    System.out.println("\n正在为表 " + table.getTableName() + " 生成代码...");
                    codeGenerator.generateCode(table);
                    System.out.println("✓ 表 " + table.getTableName() + " 的代码生成完成！");
                    successCount++;
                } catch (Exception e) {
                    System.out.println("✗ 表 " + table.getTableName() + " 的代码生成失败: " + e.getMessage());
                    failCount++;
                }
            }

            System.out.println("\n========================================");
            System.out.println("           代码生成结果统计             ");
            System.out.println("========================================");
            System.out.println("总表数: " + tables.size());
            System.out.println("成功: " + successCount);
            System.out.println("失败: " + failCount);
            System.out.println("\n输出目录: " + configManager.getOutputPath());
            
            if (failCount == 0) {
                System.out.println("\n🎉 所有代码生成成功！");
            } else {
                System.out.println("\n⚠️  部分代码生成失败，请查看错误信息");
            }

        } catch (Exception e) {
            System.out.println("\n❌ 错误: 程序执行过程中发生异常");
            System.out.println("错误详情: " + e.getMessage());
            System.out.println("\n请检查以下几点：");
            System.out.println("1. 数据库连接信息是否正确");
            System.out.println("2. 配置文件是否存在且格式正确");
            System.out.println("3. 是否有足够的文件操作权限");
            System.out.println("\n详细异常信息：");
            e.printStackTrace();
        }
    }

    /**
     * 应用表名到实体类名的映射配置
     */
    private static void applyTableEntityMapping(List<TableInfo> tables, ConfigManager configManager) {
        // 获取表名到实体类名的映射
        java.util.Map<String, String> tableEntityMapping = configManager.getTableEntityMapping();
        
        if (!tableEntityMapping.isEmpty()) {
            System.out.println("\n应用表名到实体类名的映射配置:");
            for (TableInfo table : tables) {
                String tableName = table.getTableName();
                if (tableEntityMapping.containsKey(tableName)) {
                    String entityName = tableEntityMapping.get(tableName);
                    System.out.println("- " + tableName + " -> " + entityName);
                    table.setEntityName(entityName);
                }
            }
        }
    }
}